<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Verlauf</title>
		<style>
			.linklike {
				cursor: pointer !important;
				text-decoration: underline;
			}
		</style>
		<style>
			body {
				background-color: white;
				color: black;
				margin: 10px;
			}
			.header {
				overflow: auto;
				clear: both;
			}
			.header .logo {
				float: left;
			}
			.header .form {
				float: left;
				margin-top: 22px;
				-webkit-margin-start: 12px;
			}
			.page-navigation {
				padding: 8px;
				background-color: #ebeff9;
				margin-right: 4px;
			}
			.footer {
				height: 24px;
			}
		</style>
		<style>
			#results-separator {
				margin-top: 12px;
				border-top: 1px solid #9cc2ef;
				background-color: #ebeff9;
				font-weight: bold;
				padding: 3px;
				margin-bottom: -8px;
			}
			#results-separator table {
				width: 100%;
			}
			#results-summary {
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				width: 50%;
			}
			#editing-controls button {
				margin: 18px 0 -8px 0;
			}
			#results-display {
				max-width: 740px;
				margin: 16px 0 0 0;
			}
			.day {
				color: #6a6a6a;
				font-weight: bold;
				margin: 0 0 4px 0;
				text-transform: uppercase;
				font-size: 13px;
			}
			.edit-button {
				display: inline;
				-webkit-appearance: none;
				background: none;
				border: 0;
				color: blue; /* -webkit-link makes it purple :'( */
				cursor: pointer;
				text-decoration: underline;
				padding: 0px 9px;
				display: inline-block;
				font: inherit;
			}
			.gap, .entry, .no-entries {
				margin: 0;
				padding: 0;
				list-style: none;
			}
			.gap {
				width: 35px;
				-webkit-border-end: 1px solid #ddd;
				height: 14px;
			}
			.entry {
				overflow: auto; /* Make sure it's at least as large as its children. */
			}
			.entry-box {
				cursor: default;
				line-height: 1.6em;
				/* display: -webkit-box;
				 -webkit-box-orient: horizontal; */
				max-width: 100%; /* Don't allow it to be bigger than its parent... */
				font-size: 84%;
				overflow: hidden;
			}
			html[dir=rtl] .entry-box {
				float: right; /* To make the box shrink to fit its content. */
			}
			.search-results, .day-results {
				margin: 0 0 24px 0;
				padding: 0;
			}
			.snippet {
				font-size: 12px;
				line-height: 1.6em;
				margin-bottom: 12px;
				-webkit-margin-start: 90px; /* Align it with .domain. */
				clear: both;
			}
			.entry .domain {
				color: #282;
				-webkit-padding-start: 20px;
				-webkit-padding-end: 8px;
				background-repeat: no-repeat;
				background-position-y: center;
				width: 100px;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			html[dir='rtl'] .entry .domain {
				background-position-x: right;
			}
			.entry .time {
				color: #9a9a9a;
				width: 150px;
			}
			.entry .device {
				color: #666666;
				width: 80px;
			}
			.entry input[type=checkbox] {
				position: relative;
				top: 1px;
			}
			/* Checkboxes are shown when checked or focused, or when the Entry is hovered.
			 Fade in on focus, but not on hover, because it makes the UI feel laggy. */
			.entry input[type=checkbox]:not(:checked) {
				opacity: 0;
				-webkit-transition: opacity 150ms;
			}
			.entry-box:hover input[type=checkbox], .entry-box input[type=checkbox]:focus {
				opacity: 1;
			}
			.entry-box input[type=checkbox]:focus {
				-webkit-transition: opacity 150ms;
			}
			.entry-box {
				/* background-color: none; */
				-webkit-transition: background-color 150ms;
			}
			.entry-box:hover, .entry-box.contains-focus {
				background-color: #e4ecf7;
				border-radius: 2px;
			}
			.entry .title {
				-webkit-box-flex: 1;
				white-space: nowrap;
				width: 70%;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			.entry .title > .starred {
				background-repeat: no-repeat;
				display: inline-block;
				-webkit-margin-start: 4px;
				width: 11px;
				height: 11px;
			}
			.entry .title > a {
				color: #11c;
				text-decoration: none;
			}
			.entry .title > a.to-be-removed {
				text-decoration: line-through;
			}
			.entry .title > a:hover {
				text-decoration: underline;
			}
			/* Since all history links are visited, we can make them blue. */
			.entry .title > a:visted {
				color: #11c;
			}
			.fade-out {
				opacity: 0;
				-webkit-transition: opacity 200ms;
			}
			table td {
				white-space: nowrap;
			}
		</style>
		<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
		<script type="text/javascript" src="js/daterangepicker.jQuery.js"></script>
		<link rel="stylesheet" href="css/ui.daterangepicker.css" type="text/css" />
		<link rel="stylesheet" href="css/custom-theme/jquery-ui-1.8.16.custom.css" type="text/css" title="ui-theme" />		
		<style type="text/css">
			.ui-daterangepickercontain {
				font-size: 80%;
			}
			.ui-daterangepickercontain {
				font-size: 80%;
			}
		</style>
		<script type="text/javascript">
			var bg = chrome.extension.getBackgroundPage();
			var selectionAnchor = -1;

			
			function removeVisitOld(row_id, visit_id, date) {
				alert('delete ' + visit_id);
				bg.deleteVisitWithIDAndDate(visit_id, date);

				var row = document.getElementById(row_id);
				row.parentNode.removeChild(row);
			};
			function removeVisit(visit_id, date) {			
				bg.deleteVisitWithIDAndDate(visit_id, date);				
			};

			/**
			 * Extracts and returns the domain (and subdomains) from a URL.
			 * @param {string} The url
			 * @return (string) The domain. An empty string is returned if no domain can
			 *     be found.
			 */
			function getDomainFromURL(url) {
				var domain = url.replace(/^.+:\/\//, '').match(/[^/]+/);
				return domain ? domain[0] : '';
			};

			function checkboxClicked(event) {
				
				var id = Number(this.id.slice("checkbox-".length));
				if(event.shiftKey && (selectionAnchor != -1)) {
					var checked = this.checked;
					// Set all checkboxes from the anchor up to the clicked checkbox to the
					// state of the clicked one.
					var begin = Math.min(id, selectionAnchor);
					var end = Math.max(id, selectionAnchor);
					for(var i = begin; i <= end; i++) {
						var checkbox = document.querySelector('#checkbox-' + i);
						if(checkbox)
							checkbox.checked = checked;
					}
				}
				selectionAnchor = id;

				var select1=$('.checkboxes:input[type=checkbox]:checked:not([disabled])') ;
				var anyChecked = (select1!=null && select1.length >0)?true:false;
				
				$('#remove-selected').prop("disabled", !anyChecked);
				
				
			}

			function removeItems() {
				var checked = $('.checkboxes:input[type=checkbox]:checked:not([disabled])');
				var urls = [];
				var disabledItems = [];
				var queue = [];
				var date = new Date();

				for(var i = 0; i < checked.length; i++) {
					var checkbox = checked[i];					
					var tr = checkbox.parentNode.parentNode;
					checkbox.disabled = true;
					tr.classList.add('to-be-removed');
					disabledItems.push(checkbox);
				}
				if(urls.length > 0) {
					queue.push([date, urls]);
				}
				//var question=localStrings.getString('deletewarning');
				var question="Sure to Delete?"
				if(checked.length > 0 && confirm(question)) {
					for(var i = 0; i < disabledItems.length; i++) {
						// Reload the page when the final entry has been deleted.
						var checkbox = disabledItems[i];
						var visit_id = $('#'+checkbox.id).data('visit_id');
						var date= $('#'+checkbox.id).data('date');
						
						
						//mark as deleted instead, and delete after sync
						//bg.removeVisit(visit_id,date);
						
						bg.markAsDeleted(visit_id,date);
						
						checkbox.parentNode.parentNode.parentNode.removeChild(checkbox.parentNode.parentNode);
					}
					
				} else {
					// If the remove is cancelled, return the checkboxes to their
					// enabled, non-line-through state.
					for(var i = 0; i < disabledItems.length; i++) {
						var checkbox = disabledItems[i];
						var link = checkbox.parentNode.parentNode;
						checkbox.disabled = false;
						link.classList.remove('to-be-removed');
					}
				}
				return false;
			}

			function readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset) {
				console.log("readwithrange");
				
				console.log(Date.parseExact(date_von, "dd.MM.yyyy").getTime());
				console.log(Date.parseExact(date_bis, "dd.MM.yyyy").getTime() + 25 * 60 * 60 * 1000);

				bg.readVisits(keyword,Date.parseExact(date_von, "dd.MM.yyyy").getTime(), Date.parseExact(date_bis, "dd.MM.yyyy").getTime() + 25 * 60 * 60 * 1000, orderby,limit,offset,function(dataset) {
					var dataset_length=dataset.length;				
					console.log(dataset.length);

					var bdown = '<img src=\"img/bullet_arrow_down.png\">';
					var bup = '<img src=\"img/bullet_arrow_up.png\">';

					var img1 = '';
					var img2 = '';
					var img3 = '';
					var img4 = '';
					var img5 = '';

					switch(orderby) {
						case "date ASC":
							img5 = bup;
							break;
						case "date DESC":
							img5 = bdown;
							break;
						case "device_id ASC":
							img4 = bup;
							break;
						case "device_id DESC":
							img4 = bdown;
							break;
						case "link ASC":
							img3 = bup;
							break;
						case "link DESC":
							img3 = bdown;
							break;
						case "title ASC":
							img2 = bup;
							break;
						case "title DESC":
							img2 = bdown;
							break;
						case "id ASC":
							img1 = bup;
							break;
						case "id DESC":
							img1 = bdown;
							break;
						default:

							break;
					}

					var table = "";
					var tableBegin = '<table cellspacing="0"><tr class="linklike entry-box"><td><input type="checkbox" id="checkboxAll"></td><td id=\"orderby5\">Time ' + img5 + '</td><td id=\"orderby4\">Device ' + img4 + '</td><td id=\"orderby3\">Adress ' + img3 + '</td><td id="orderby2">Title ' + img2 + '</td></tr>';
					var tableEnd = '</table>';
					table += tableBegin;
					var row = "";
					for(var i = 0; i < dataset.length; i++) {
						//TODO verkuerzen, nicht nur fuer title
						var strtmp = dataset[i].title;
						if(!strtmp) {
							//strtmp = "(no title)";
							strtmp = "";
						}
						
						
						//TODO Besser Escapen/ umkodieren whatever , und nicht nur fuer title
						strtmp = decodeURIComponent(strtmp);
						row = '<tr id="row' + i + '" class="entry entry-box" for="checkboxAll">';
						row += '<td ><input type="checkbox" class="checkboxes" id="checkbox-' + i + '" data-visit_id="'+dataset[i].id+'" data-date="'+dataset[i].date+'"></td>';
						row += '<td ><div class="time">' + new Date(dataset[i].date).toString("HH:mm:ss dd.MM.yyyy") + '</div></td>';
						row += '<td><div class="device">' + dataset[i].device + '</div></td>';
						row += '<td><div class="domain" style="background-image: url(chrome://favicon/' + dataset[i].link + '); ">' + getDomainFromURL(dataset[i].link) + '</div></td>';
						row += '<td><div class="title"><a href="' + dataset[i].link + '" id="id-0" title="' + dataset[i].link + '">' + strtmp + '</a></div></td>';
						
						row += '</tr>';

						// row='<tr id=\"row'+i+'\"><td>'+dataset[i].id+'</td><td><img src=\"chrome://favicon/'+dataset[i].link+'\">'+strtmp+'</td><td>'+dataset[i].link+'</td><td>'+dataset[i].device+'</td><td>'+new Date(dataset[i].date).toString('yyyy.M.d')+'</td><td> <button type="button" onclick=\'removeVisit(\"row'+i+'\",\"'+dataset[i].id+'\",\"'+dataset[i].date+'\"    );\'>x</button>  </td></tr>';
						table += row;
					};
					table += tableEnd;

					
					$('#results-display').html(table);
					// $(".linklike").click(function(){
					// alert('wr3');
					// });
					
					var pages='';
					var older='';
					var newer='';
					var newest='';
					
					var newer_offset=offset-limit;
					var newest_offset=0;
					var older_offset=offset+limit;
										
					
					if(dataset_length==limit){
						older='<a id="older" href="#history-section">Older</a>';					
					}					
					
					
					if(offset && offset>0){
						newer='<a id="newer" href="#history-section">Never</a> ';
						newest='<a id="newest" href="#history-section">Newest</a> ';
					}					
					
					pages=newest+newer+older;
					
					$('#results-pagination').html(pages);


					if(dataset_length==limit){
						$('#older').click(function() {
							readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,older_offset);
						});					
					}					
					
					if(offset && offset>0){
					$('#newer').click(function() {
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,newer_offset);
					});
					
					$('#newest').click(function() {
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,newest_offset);
					});
					}
					
					
					$('#orderby1').click(function() {
						if(orderby == "id ASC") {
							orderby = "id DESC";
						} else {
							orderby = "id ASC";
						}
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset);
					});
					$('#orderby2').click(function() {
						if(orderby == "title ASC") {
							orderby = "title DESC";
						} else {
							orderby = "title ASC";
						}
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset);
					});
					$('#orderby3').click(function() {
						if(orderby == "link ASC") {
							orderby = "link DESC";
						} else {
							orderby = "link ASC";
						}
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset);
					});
					$('#orderby4').click(function() {
						if(orderby == "device_id ASC") {
							orderby = "device_id DESC";
						} else {
							orderby = "device_id ASC";
						}
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset);
					});
					$('#orderby5').click(function() {
						if(orderby == "date DESC") {
							orderby = "date ASC";
						} else {
							orderby = "date DESC";
						}
						readAndPrintWithDateRange(keyword,date_von, date_bis, orderby,limit,offset);
					});
					$('#checkboxAll').click(function() {
						if(!$('#checkboxAll').prop("checked")) {
							$(".checkboxes").prop("checked", false);
							$('#remove-selected').prop("disabled", true);
							
						} else {
							$(".checkboxes").prop("checked", true);
							$('#remove-selected').prop("disabled", false);
						}
					});
					$('.checkboxes').bind('click', checkboxClicked);					
					$('#remove-selected').click(function() {
						if(!this.disabled) {
							removeItems();
						}
					});
					
				});
			};

			function registerClicks() {
				$('#submit_b').click(function() {
					var daterange = $('#datepicker').val().split(" - ");

					var date_von = daterange[0];
					var date_bis = daterange[1];

					if(daterange.length == 1) {
						date_bis = date_von;
					}
					
					var keyword = $('#term').val();

					readAndPrintWithDateRange(keyword,date_von, date_bis, 'date DESC',100,0);
				});

				$('#drptbls').click(function() {
					bg.dropTables();
					alert("restart browser");
				});
				$('#button4').click(function() {

					var link = $('#link_1').val();
					var title = $('#title_1').val();
					var device = $('#device_1').val();
					var date = $('#date_1').val();

					bg.insertdevice(device, function(device_id, success) {
						bg.addVisit(link, title, device_id, Date.parse(date));
					});
				});
				$('#button5').click(function() {
					console.log('getAll1');
					bg.getAllHistory();
					console.log('getAll11');
				});
				$('#button6').click(function() {
					//test1
					localStorage.setItem('logging1', "test log1111");

					//bg.test12345()
					console.log('show localStorage');

					console.log('show logs');
					var locstor = $('#locstor').val();
					$('#dataset').html(localStorage.getItem(locstor));
				});
				
				
				$('#rstevery').click(function() {
					
					localStorage["installDone"]='true';
					bg.dropTables();
					alert("restart browser");
				});
				
				$('#dbgstf').click(function() {
					$('#debugstuff').toggle();
				});			
				
			};

			$(function() {
				registerClicks();
				
				$('#datepicker').daterangepicker({
					dateFormat : 'dd.mm.yy',
				});

				$("#datepicker").val(new Date().toString("dd.MM.yyyy"));
				
				//first search
				$('#submit_b').click();
				
				//show debug stuff
				$('#debugstuff').toggle();
			});

		</script>
	</head>
	<body style="font-family: Arial, sans-serif; font-size: 84%; ">
		<div class="header">
			<a id="history-section" href=""> <img src="" width="67" height="67" class="logo" border="0"></a>
			<div id="search-form" class="form">
				<input type="text" name="term" id="term">
				<input type="text" name="datepicker" id="datepicker" size="30" />
				<input type="submit" name="submit" i18n-values="value:searchbutton" value="Search History" id="submit_b">
				<span id="debugstuff" hidden="true"><b>|</b> <b><span id="dbgstf">Debugstuff:</span></b> <button type="button" id="drptbls">dropTablesOnly</button> <button type="button" id="rstevery">Reset-Everything</button> </span>
			</div>
		</div>
		<div class="main">
			<div id="results-separator">
				<table border="0" cellpadding="0" cellspacing="0">
					<tbody>
						<tr>
							<td id="results-summary">History</td><td id="edit-button"><p></p></td>
						</tr>
					</tbody>
				</table>
			</div>
			<div id="editing-controls">
				<!--
				<button id="clear-browsing-data" i18n-content="clearallhistory">
					Alle Internetdaten löschen...
				</button>
				-->
				<button id="remove-selected" disabled="disabled" i18n-content="removeselected">
					Remove Selected Items
				</button>
			</div>
			<div id="results-display"></div>
			<div id="results-pagination">							
			</div>
		</div>
		<div class="footer"></div>
	</body>
</html>